package com.wuchao.exception;

import com.wuchao.response.R;
import com.wuchao.response.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Author wuchao66
 * @Date 2023/2/17 15:03
 * @PackageName:com.wuchao.exception
 * @ClassName: GlobalExceptionHandle
 * @Description: TODO
 * @Param
 * @Version 1.0
 */
//拦截controller 全局异常
@RestControllerAdvice
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandle {
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public R exceptionHandler(Exception e){
//        if(e instanceof ArrayIndexOutOfBoundsException){
//            log.info("数组越界错误");
//            return R.error(ResultCode.SHUZUOUT);
//        }
        //算数错误
        if (e instanceof ArithmeticException){
            log.info("算数错误");
            return R.error(ResultCode.ARITHMETIC_EXCEPTION);
        }else if(e instanceof NullPointerException){
            log.info("空指针异常");
            return  R.error(ResultCode.NULL_PONIT);
        }
        else if(e instanceof ArrayIndexOutOfBoundsException) {
            return R.error(ResultCode.COMMON_FAIL);
        }
        else  if(e instanceof BusinessException){
            return R.error().code(ResultCode.BU_ERROR.getCode())
                    .message(ResultCode.BU_ERROR.getMessage());
        }
        else if(e instanceof BusinessException){
            //借马换马
           return  R.error()
                   .code(((BusinessException)e).getCode())
                   .message(((BusinessException)e).getErrMsg());
        }

        else{
            return R.error();//有重载的
        }

    }
}
